﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;


using Coding4Fun.Cannon.TechEdPhone.Complete.Cannon;
using Microsoft.Devices.Sensors;


namespace Coding4Fun.Cannon.TechEdPhone.Complete.Controls
{
	public partial class DriveView
	{
		private DrivingMode _drivingMode = DrivingMode.Forward;
		private bool _isDriving = false;

		void SetMode(DrivingMode newmode)
		{
			if (newmode == _drivingMode)
				return;

			_drivingMode = newmode;
		}


		private void ForwardIcon_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			uxShifter.Value = (int)DrivingMode.Forward;
		}

		private void ReverseIcon_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			uxShifter.Value = (int)DrivingMode.Reverse;
		}

		private void Shifter_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
		{
			SetMode(Math.Round(e.NewValue) == 1 ? DrivingMode.Forward : DrivingMode.Reverse);

		}

		private void Drive(int leftEngine, int rightEngine)
		{
			App.Service.Drive(leftEngine, rightEngine);

			LeftEngine.Text = leftEngine.ToString();
			RightEngine.Text = rightEngine.ToString();
		}


		private void uxGasPedal_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
		{
			_isDriving = true;

		}

		private void uxGasPedal_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
		{
			_isDriving = false;

			Drive(0, 0);
			Drive(0, 0);
		}
		
		public override void AccelerometerReadingChanged(SensorData<AccelerometerReading> data)
		{
		   if (_isDriving)
			  CalculateDrive(data.Value.Y);
		}

		private void CalculateDrive(double yAxis)
		{
			if (!_isDriving)
				return;

			int leftEngine;
			int rightEngine;

			SetEngineSpeed(out leftEngine, out rightEngine, _drivingMode, yAxis);

			Drive(leftEngine, rightEngine);
		}

		const int FastWheel = 80;
		const int SlowWheel = -20;
		const int DefaultWheel = 40;

		public static void SetEngineSpeed(out int leftEngine, out int rightEngine, DrivingMode drive, double yAxis)
		{
			leftEngine = DefaultWheel;
			rightEngine = DefaultWheel;

			var turn = CannonUtility.GetTurn(yAxis);

			switch (turn)
			{
				case TurningAction.Left:
					leftEngine = SlowWheel;
					rightEngine = FastWheel;
					break;
				case TurningAction.Right:
					rightEngine = SlowWheel;
					leftEngine = FastWheel;
					break;
				default:
					break;
			}


			if (drive == DrivingMode.Reverse)
			{
				leftEngine *= -1;
				rightEngine *= -1;
			}
		}
	}
}
